﻿using MongoDB.Bson;
using MongoDB.Driver;
using SupermarkedModel;
using System;
using System.Linq;

namespace Supermarket.Client
{
    internal static class ProductReportGenerator
    {
        public static void GenerateProductReport()
        {

            MongoClient mongoClient = new MongoClient("mongodb://localhost/");
            MongoServer mongoServer = mongoClient.GetServer();
            MongoDatabase db = mongoServer.GetDatabase("SupermarketDB");
            MongoCollection<BsonDocument> productCollection = db.GetCollection("Products");
            MongoCollection<BsonDocument> vendorExpensesCollection = db.GetCollection("VendorExpenses");

            SupermarketDbEntities entities = new SupermarketDbEntities();

            foreach (var vendor in entities.Vendors)
            {
                QueryDocument queryExpense = new QueryDocument("vendor-name", vendor.VendorName);
                var expensesCollection = vendorExpensesCollection.Find(queryExpense);
                var expensesBson = expensesCollection.FirstOrDefault();
                decimal expenses;

                if (expensesBson == null)
                {
                    expenses = 0;
                }
                else
                {
                    expenses = Decimal.Parse(expensesBson.ToString());
                }

                QueryDocument queryIncome = new QueryDocument("vendor-name", vendor.VendorName);
                var incomesCollection = productCollection.Find(queryIncome);
                decimal incomes;
                if (incomesCollection != null && incomesCollection.Count() == 0)
                {
                    incomes = 0;
                    foreach (var income in incomesCollection)
                    {
                        incomes += Decimal.Parse(income.ToString());
                    }
                }
                else
                {
                    incomes = 0;
                }

                //Console.WriteLine(vendor.VendorName + " " + incomes + " " + expenses + " " + (incomes - Decimal.Parse(expenses.ToString())));
            }
        }
    }
}
